import Vue from 'vue'
import VueRouter from 'vue-router'
// import login from '@/views/login.vue'
// import register from '../views/register.vue'
// import layout from '../views/layout.vue'
// import detail from '../views/detail.vue'

// import article from '../views/article.vue'
// import collect from '../views/collect.vue'
// import like from '../views/like.vue'
// import user from '../views/user.vue'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  // 一级路由
  // 登录 /注册 /首页 /详情
  { path: '/login', component: () => import('@/views/login.vue') },
  { path: '/register', component: () => import('../views/register.vue') },
  {
    path: '/',
    component: () => import('../views/layout.vue'),
    // 重定向
    redirect: '/article',
    children: [
      { path: '/article', component: () => import('../views/article.vue') },
      { path: '/collect', component: () => import('../views/collect.vue') },
      { path: '/like', component: () => import('../views/like.vue') },
      { path: '/user', component: () => import('../views/user.vue') }

    ]
  },
  { path: '/detail/:id', component: () => import('../views/detail.vue') }

]

const router = new VueRouter({
  routes
})
// 注册全局前置守卫
// router.beforeEach
// 传一个回调函数
// 函数里面有三个参数
// to:到哪去
// from:从哪里来
// next:函数
router.beforeEach((to, from, next) => {
  // 调用next（）表示放行,调用next(false)表示不放行,调用next('路径') 表示强行跳转到指定路径
  // 由于不放行就会瘫痪
  // next()
  const token = getToken()
  if (token) {
    // 放行
    next()
  } else {
    // 判断要访问的页面是否在白名单
    const whiteList = ['/login', '/register']
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      Toast.fail('您还没登录呢，大宝贝')
    }
  }
})

export default router
